﻿// Inner Fire 游戏引擎库
// MapObject - 地图对象
//
// Copyright (c) 2025 by 尔西大帝. All rights reserved.
//
// 所属层级：应用层（4）
// 用于游戏的地图。我居然想到把整个地图都做为一个对象。简直丧心病狂。
//
// Author: 尔西大帝
// Email: 2670613871@qq.com
// Created: 2025-06-14

#include "map_object.h"

namespace ifire::game {
MapObject::MapObject(ikit::sstr name, Scene* scene, GameObject* parent)
    : GameObject(name, scene, parent) {}

MapObject::~MapObject() {}

void MapObject::SetInfo(const SimpleMap* map, const MapSetting* setting) {
  map_ = map;
  setting_ = setting;
}

void MapObject::SetPosition(IVec3 position) {}

void MapObject::FixedUpdate() {}

void MapObject::SetTerrainBlocks(dx::MapBlocks* blocks) {
  terrain_blocks_ = blocks;

  XMFLOAT3 pos(0.0f, 0.0f, 0.0f);
  XMFLOAT3 rot(0.0f, 0.0f, 0.0f);
  XMFLOAT3 scl(1.0f, 1.0f, 1.0f);
  XMFLOAT2 tex_offset(0.0f, 0.0f);

  float grid_size = 2.0f;
  float y_height = 1.0f;
  float tex_grid = 0.25;
  float sea_level = setting_->sea_level * y_height;

  float offset_x = map_->width * 0.5f * -grid_size;
  float offset_y = map_->height * 0.5f * -grid_size;

  // 对每个Block进行设置
  for (int y = 0; y < map_->height; y++) {
    for (int x = 0; x < map_->width; x++) {
      int index = y * map_->width + x;
      int height = map_->heights->at(index);

      int terrain_code = map_->terrain->at(index);
      auto& terrain = setting_->GetTerrain(terrain_code);

      pos.x = x * grid_size + offset_x;
      pos.y = height * y_height - sea_level;
      pos.z = y * grid_size + offset_y;

      tex_offset.x = tex_grid * terrain.tex.x;
      tex_offset.y = tex_grid * terrain.tex.y;

      terrain_blocks_->SetBlock(index, pos, rot, scl, tex_offset);
    }
  }
}

} // namespace ifire::game